package com.sxkiler.demo.rpc.server;

import com.alibaba.nacos.api.naming.pojo.Instance;
import com.sxkiler.demo.rpc.common.InitAnnotatedObject;
import com.sxkiler.demo.rpc.nacos.NacosTemplate;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.Map;

public class RpcServer {
    public static void startserver(int port){
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new MessageDecoder());//自定义的解码器
                            pipeline.addLast(new MessageEncoder());//自定义的编码器
                            pipeline.addLast(new RpcServerHandler());
                        }
                    });
            ChannelFuture future = bootstrap.bind(port).sync();
            if (future.isSuccess()){
                //将带有@RpcService注解的类加载到“Bean容器”中
                Map<String,Object> beans = InitAnnotatedObject.init();
                //将带有@RpcService注解的类注册到Nacos中
                beans.forEach((name,obj)->{
                    Instance instance = new Instance();
                    instance.setServiceName(name);
                    instance.setPort(port);
                    instance.setIp("127.0.0.1");
                    NacosTemplate.registerServer(instance);
                });
                System.out.println("成功加载bean,数量："+beans.size());
                System.out.println("已加载的beans：--["+beans.toString()+"]--");
                System.out.println("服务器已启动。。。");
            }
            future.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        startserver(1089);
    }
}


